<template>
	<view class="uni-flex uni-column">
		<!-- #ifdef MP-WEIXIN  -->
		<view class="login-wx uni-flex uni-column">
			<view class="logo">
				<image :src="$getCloudStorageUrl('/logo.jpg')"></image>
				<view class="uni-text-big uni-bold">第三空间吃喝玩乐聚</view>
			</view>
			<button :disabled="busy || !wxLoginCode" class="btn-login-wx" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
				<view class="btn-login-wx-content uni-flex align-center">
					<!-- <image :src="$getCloudStorageUrl('/weixin.png')"></image> -->
					<text>手机号快捷登录</text>
				</view>
			</button>
			<view class="h-box justify-center question-wrapper mg-t-sm">
				<u-button size="mini" openType="contact">
					<view class="h-box">
						<text class="mg-r-xs text-sm">无法登陆</text>
						<u-icon name="question-circle" size="24"></u-icon>
					</view>
				</u-button>
			</view>
		</view>
		<!-- #endif -->
		<!-- #ifndef MP -->
		<view class="login-view h-fill pad">
			<view class="login-view-title uni-center">登陆</view>
			<view class="login-view-form uni-flex uni-column">
				<view class="login-view-form-item uni-flex align-center">
					<text class="login-view-form-item-label">用户名</text>
					<input class="login-view-form-item-input uni-flex-extend" v-model="username" />
				</view>
				<view class="login-view-form-item uni-flex align-center">
					<text class="login-view-form-item-label">密码</text>
					<input class="login-view-form-item-input uni-flex-extend" v-model="password" password />
				</view>
			</view>
			<button class="login-view-btn" type="primary" @click="loginWithPwd">登陆</button>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState,
		mapGetters,
		mapActions
	} from 'vuex';
	import Api from '@/common/api';
	import {
		loginByWeiXin,
		loginWithPwd,
		getNeareastCity
	} from "../../api/platform/user.js"
	export default {
		data() {
			return {
				busy: false,
				username: "",
				password: "",
				wxLoginCode: ""
			};
		},
		computed: {
			...mapGetters({
				isTokenValid: 'isTokenValid'
			})
		},
		onLoad() {
			this.logout()
			let username = uni.getStorageSync("username");
			if (username) {
				this.username = username;
			}
			let password = uni.getStorageSync("password");
			if (password) {
				this.password = password;
			}
		},
		async onReady() {
			//#ifdef MP-WEIXIN
			this.wxLogin({});
			//#endif
		},
		onBackPress() {
			this.finishLogin();
		},
		beforeDestroy() {
			this.clearTimer()
		},
		methods: {
			...mapMutations(['updateToken', 'login','logout', 'updateUserInfo', 'finishLogin', 'setWxLoginCode']),
			...mapActions(['getCity']),
			onGetUserInfo: function(res) {
				console.log('get user info', res);
				this.doLogin(res.detail);
			},
			onGetPhoneNumber(res) {
				if (res.detail.encryptedData) {
					this.doLoginWithMobileData(res.detail)
				}
			},
			async wxLogin({showLoading = true}) {
				this.clearTimer()
				if(showLoading) {
					uni.showLoading({
						mask: true
					})
				}
				let [err, res] = await uni.login();
				if (err) {
					this.$log("获取小程序登录码遇到错误", err);
					uni.showModal({
						title: "小程序码获取失败，请稍后重试！",
						cancelText: "回主页",
						confirmText: "重试",
						success: (res) => {
							if (res.confirm) {
								this.wxLogin()
							} else {
								uni.reLaunch({
									url: "/pages/platform/goods-list"
								})
							}
						}
					})
					if(showLoading) {
						uni.hideLoading()
					}
					return;
				}
				this.wxLoginCode = res.code;
				console.log('wxLoginCode', res.code)
				this.setWxLoginCode(res.code)
				this.timer = setInterval(() => {
					this.wxLogin({})
				}, 5 * 60 * 1000)
				if (showLoading) {
					uni.hideLoading();
				}
			},
			clearTimer() {
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
			},
			async loginWithPwd() {
				// if (this.isTokenValid) {
				// 	uni.navigateBack()
				// 	return
				// }
				if (this.busy) {
					return
				}
				if (!this.username) {
					uni.showToast({
						icon: "none",
						title: "请输入用户名"
					})
					return;
				}
				if (!this.password) {
					uni.showToast({
						icon: "none",
						title: "请输入密码"
					})
					return;
				}
				uni.setStorageSync("username", this.username);
				uni.setStorageSync("password", this.password);
				this.busy = true
				try {
					let res = await loginWithPwd({
						username: this.username,
						password: this.password
					})
					this.updateToken({
						token: res.tokenInfo.token,
						tokenExpired: res.tokenInfo.expired
					})
					this.login(res.userInfo)
					uni.navigateBack()
				} catch (e) {
					console.error(e)
				} finally {
					this.busy = false
				}
			},
			async doLogin(wxUserInfo) {
				// if (this.isTokenValid) {
				// 	uni.navigateBack()
				// 	return
				// }
				if (this.busy) {
					reutrn
				}
				this.busy = true;
				uni.showLoading({
					mask: true
				})
				try {
					let res = await loginByWeiXin({
						showLoading: false,
						code: this.wxLoginCode,
						wxUserInfo: {
							encryptedData: wxUserInfo.encryptedData,
							iv: wxUserInfo.iv
						}
					})
					this.updateToken({
						token: res.tokenInfo.token,
						tokenExpired: res.tokenInfo.expired
					})
					this.login(res.userInfo)
					uni.navigateBack()
				} catch (e) {
					this.$log("登陆遇到错误", e);
					this.wxLogin({})
					uni.hideLoading()
				} finally {
					this.busy = false;
				}
			},
			
			async doLoginWithMobileData(mobileData) {
				// console.log('mobileData: ',mobileData);
				// if (this.isTokenValid) {
				// 	uni.navigateBack()
				// 	return
				// }
				if (this.busy) {
					reutrn
				}
				this.busy = true;
				uni.showLoading({
					mask: true
				})
				try {
					let res = await loginByWeiXin({
						showLoading: false,
						code: this.wxLoginCode,
						wxMobileData: {
							encryptedData: mobileData.encryptedData,
							iv: mobileData.iv
						}
					})
					uni.hideLoading()
					this.updateToken({
						token: res.tokenInfo.token,
						tokenExpired: res.tokenInfo.expired
					})
					this.login(res.userInfo)
					uni.navigateBack()
				} catch (e) {
					uni.hideLoading()
					console.error(e)
					await this.wxLogin({showLoading: false})
				} finally {
					this.busy = false;
				}
			},
		}
	};
</script>

<style>
	page {
		background: #fff;
	}
</style>
<style scoped lang="scss">
	/deep/ .question-wrapper .u-btn::after {
		border: 0 !important;
	}

	.login-wx {
		height: 100vh;
		justify-content: center;

		.logo {
			text-align: center;

			image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 60rpx;
			}

			margin-bottom: 80rpx;
		}

		.btn-login-wx {
			background-color: #00cd62;
			color: #fff;
			border-radius: 60rpx;
			padding: 0 40rpx;

			&-content {
				height: 100%;

				image {
					width: 60rpx;
					height: 60rpx;
					margin-right: $uni-spacing-row-base;
				}
			}
		}
	}

	.login-view {
		&-title {
			font-size: 36rpx;
			font-weight: bold;
		}

		&-form {
			margin: 20rpx 0;
			background-color: #FFFFFF;
			border-radius: 20rpx;
			padding: 10rpx 20rpx;

			&-item {
				padding: 10rpx 0;

				&-label {
					width: 20%;
					margin-right: 20rpx;
				}

				&-input {
					background-color: #F2F2F2;
					padding: 0 10rpx;
					font-size: 30rpx;
				}
			}
		}

		&-btn {
			border-radius: 40rpx;
		}
	}
</style>
